package cn.shujuhai.common.controller.common;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: NiuYaHu
 * @Date: 2025/4/22 15:03
 * @Description:
 **/

@RestController
@RequestMapping("/captcha")
@CrossOrigin
public class CaptchaController {
    private static final Map<String, Integer> captchaCache = new HashMap<>();

    @GetMapping("/generate")
    public Map<String, String> generateCaptcha() {
        // 生成验证码数据
        String captchaId = java.util.UUID.randomUUID().toString();
        int correctX = 100 + (int) (Math.random() * 140);
        captchaCache.put(captchaId, correctX);

        // 返回验证码的背景图片路径、滑块路径等信息
        Map<String, String> response = new HashMap<>();
        response.put("captchaId", captchaId);
        response.put("correctX", String.valueOf(correctX));
        return response;
    }

    public static boolean verifyCaptcha(String captchaId, Integer userX) {
        // 验证滑块轨迹

        int correctX = captchaCache.getOrDefault(captchaId, -1);
        captchaCache.remove(captchaId);
        if (correctX == -1) {
            return false;
        }
        // 允许一定的误差范围
        int threshold = 20;
        return Math.abs(userX - correctX) <= threshold;
    }
}
